<template>
  <div class="user">
    <basic-container>
      <avue-crud :option="option"
                 ref="crud"
                 v-model="form"
                 :page="page"
                 @on-load="getList"
                 :table-loading="listLoading"
                 @search-change="handleFilter"
                 @refresh-change="handleRefreshChange"
                 @row-update="update"
                 @row-save="create"
                 :before-open="handleOpenBefore"
                 @row-click="rowClick"
                 :data="list">
        <template slot="menuLeft">
          <el-button v-if="sys_user_add"
                     class="filter-item"
                     @click="handleCreate"
                     size="small"
                     type="primary"
                     icon="el-icon-edit">添加
          </el-button>
          <el-button v-if="sys_user_role_add"
                     class="filter-item"
                     @click="handleRoleAdd"
                     size="small"
                     type="primary"
                     icon="el-icon-edit">分配角色
          </el-button>
          <el-button v-if="sys_password_reset"
                     class="filter-item"
                     @click="handlePasswordReset"
                     size="small"
                     type="primary"
                     icon="el-icon-edit">重置密码
          </el-button>
        </template>
        <template slot="username"
                  slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
        <template slot="role"
                  slot-scope="scope">
              <span v-for="(role,index) in scope.row.roleList"
                    :key="index">
                <el-tag>{{role.roleName}} </el-tag>&nbsp;&nbsp;
              </span>
        </template>
        <template slot="deptId"
                  slot-scope="scope">
          {{scope.row.deptName}}
        </template>
        <template slot="lockFlag"
                  slot-scope="scope">
          <el-tag>{{scope.label}}</el-tag>
        </template>
        <template slot="menu"
                  slot-scope="scope">
          <el-button v-if="sys_user_edit"
                     size="small"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row,scope.index)">编辑
          </el-button>
          <el-button v-if="sys_user_del"
                     size="small"
                     type="text"
                     icon="el-icon-delete"
                     @click="deletes(scope.row,scope.index)">删除
          </el-button>
          <el-button v-if="sys_user_menu_add"
                     size="small"
                     type="text"
                     icon="el-icon-plus"
                     @click="handlePermission(scope.row,scope.index)">权限
          </el-button>
        </template>
        <template slot="deptIdForm"
                  slot-scope="scope">
          <avue-crud-input v-model="form.deptId"
                           type="tree"
                           placeholder="请选择所属部门"
                           :node-click="getNodeData"
                           :dic="treeDeptData"
                           :props="defaultProps"></avue-crud-input>
        </template>
        <template slot="roleForm"
                  slot-scope="scope">
          <avue-crud-select v-model="role"
                            multiple
                            placeholder="请选择角色"
                            :dic="rolesOptions"
                            :props="roleProps"></avue-crud-select>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog title="分配权限"
               :visible.sync="dialogPermissionVisible">
      <el-row>
        <el-col :span="10" :offset="4">加权限</el-col>
        <el-col :span="10">减权限</el-col>
      </el-row>
      <el-row>
        <el-col :span="10" :offset="4">
          <el-tree class="filter-tree"
                   :data="plusPermissionTreeData"
                   :default-checked-keys="plusPermissionCheckedKeys"
                   :check-strictly="true"
                   node-key="id"
                   highlight-current
                   :props="defaultProps"
                   show-checkbox
                   ref="plusMenuTree"
                   :filter-node-method="filterNode"
                   @check-change="(data,isSelected)=>handleNodeChange('plusMenuTree',data,isSelected)"
                   default-expand-all>
          </el-tree>
        </el-col>
        <el-col :span="10">
          <el-tree class="filter-tree"
                   :data="reducePermissionTreeData"
                   :default-checked-keys="reducePermissionCheckedKeys"
                   :check-strictly="true"
                   node-key="id"
                   highlight-current
                   :props="defaultProps"
                   show-checkbox
                   ref="reduceMenuTree"
                   :filter-node-method="filterNode"
                   @check-change="(data,isSelected)=>handleNodeChange('reduceMenuTree',data,isSelected)"
                   default-expand-all>
          </el-tree>
        </el-col>
      </el-row>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="updatePermession(userId, userName)">更 新
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配角色"
               :visible.sync="dialogRoleVisible">
      <avue-crud-select v-model="role"
                        multiple
                        placeholder="请选择角色"
                        :dic="rolesOptions"
                        :props="roleProps"></avue-crud-select>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="updateUserRole()">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchUserMenuTree,fetchMenuTree,GetMenu,userMenuUpdate} from "@/api/admin/menu";
  import {addObj, delObj, fetchList, getObj, putObj,resetPassword} from "@/api/admin/user";
  import {deptRoleList,userRoleUpd} from "@/api/admin/role";
  import {fetchTree} from "@/api/admin/dept";
  import {tableOption} from '@/const/crud/admin/user';
  import {mapGetters} from "vuex";
  import { Loading } from 'element-ui';
  import {constants} from 'fs';
  import {connect} from 'tls';

  export default {
    name: "table_user",
    data() {
      return {
        option: tableOption,
        treeDeptData: [],
        checkedKeys: [],
        roleProps: {
          label: "roleName",
          value: 'roleId'
        },
        plusPermissionTreeData: [],//当前用户的权限列表
        reducePermissionTreeData: [],//当前用户的权限列表
        plusPermissionCheckedKeys: [],//当前用户的自定义增加的权限
        reducePermissionCheckedKeys: [],//当前用户的自定义减少的权限
        dialogPermissionVisible: false,//是否弹出分配权限对话框
        defaultProps: {
          label: "name",
          value: 'id',
        },
        userMenuDTO:{
          userId:undefined,//当前设置权限的用户ID
          userName:undefined,//当前设置权限的用户名
          plusMenuIds:'', //增加的权限
          reduceMenuIds:'',//减少的权限
        },
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20, // 每页显示多少条,
          isAsc: false//是否倒序
        },
        list: [],
        listLoading: true,
        role: [],
        form: {},
        rolesOptions: [],
        currentSelectedRow: undefined,//当前表格选择的行
        dialogRoleVisible: false,//分配角色对话框是否展示
        updateRoleDTO:{
          userId:undefined,
          roleIds:[]
        },//分配角色的参数
      };
    },
    computed: {
      ...mapGetters(["permissions"])
    },
    watch: {
      role() {
        this.form.role = this.role
      }
    },
    created() {
      this.sys_user_add = this.permissions["sys_user_add"];
      this.sys_user_edit = this.permissions["sys_user_edit"];
      this.sys_user_del = this.permissions["sys_user_del"];
      this.sys_user_menu_add = this.permissions["sys_user_menu_add"];
      this.sys_user_role_add = this.permissions["sys_user_role_add"];
      this.sys_password_reset = this.permissions["sys_password_reset"];
    },
    methods: {
      getList(page, params) {
        this.listLoading = true;
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params)).then(response => {
          this.list = response.data.data.records;
          this.page.total = response.data.data.total
          this.listLoading = false;
        });
      },
      getNodeData(data) {
        deptRoleList().then(response => {
          this.rolesOptions = response.data.data;
        });
      },
      handleDept() {
        fetchTree().then(response => {
          this.treeDeptData = response.data.data;
        });
      },
      handleFilter(param) {
        this.page.page = 1;
        this.getList(this.page, param);
      },
      handleRefreshChange() {
        this.getList(this.page)
      },
      handleCreate() {
        this.$refs.crud.rowAdd();
      },
      handleOpenBefore(show, type) {
        window.boxType = type;
        this.handleDept();
        if (['edit', 'views'].includes(type)) {
          this.role = [];
          for (var i = 0; i < this.form.roleList.length; i++) {
            this.role[i] = this.form.roleList[i].roleId;
          }
          deptRoleList().then(response => {
            this.rolesOptions = response.data.data;
          });
        } else if (type === 'add') {
          this.role = [];
        }
        show();
      },
      handleUpdate(row, index) {
        this.$refs.crud.rowEdit(row, index);
        this.form.password = undefined
      },
      create(row, done, loading) {
        addObj(this.form).then(() => {
          this.getList(this.page);
          done();
          this.$notify({
            title: "成功",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        }).catch(() => {
          loading();
        });
      },
      update(row, index, done, loading) {
        putObj(this.form).then(() => {
          this.getList(this.page);
          done();
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        }).catch(() => {
          loading();
        });
      },
      deletes(row, index) {
        this.$confirm(
          "此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          delObj(row.userId)
            .then(() => {
              this.list.splice(index, 1);
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000
              });
            })
            .cache(() => {
              this.$notify({
                title: "失败",
                message: "删除失败",
                type: "error",
                duration: 2000
              });
            });
        });
      },
      handlePermission(row, index){
        //加权限
        fetchUserMenuTree(row.userId,1)
          .then(response => {
            console.log("加权限:",response);
            this.plusPermissionCheckedKeys = response.data;
            //减权限
            return fetchUserMenuTree(row.userId,2)
          }).then(response => {
            console.log("减权限:",response);
            this.reducePermissionCheckedKeys = response.data;
            //获取所有的菜单权限
            return GetMenu();
          }).then(response => {
            console.log("当前用户的权限:",response);
            this.plusPermissionTreeData = response.data.data;
            this.reducePermissionTreeData = response.data.data;

            //设置更新权限的方法参数
            this.userId = row.userId;
            this.userName = row.userName;
            // 弹出对话框
            this.dialogPermissionVisible = true;
          });
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1
      },
      handleNodeChange(treeName,data,isSelected){
        console.log("节点状态改变:",treeName,data,isSelected);
        if(!isSelected){
          return;
        }
        if(treeName==='plusMenuTree'){
          this.$refs.reduceMenuTree.setChecked(data,!isSelected,false);
        }
        if(treeName==='reduceMenuTree'){
          this.$refs.plusMenuTree.setChecked(data,!isSelected,false);
        }
      },
      updatePermession(userId,userName){
        this.userMenuDTO.userId = userId;
        this.userMenuDTO.plusMenuIds = '';
        this.userMenuDTO.reduceMenuIds = '';
        this.userMenuDTO.plusMenuIds = this.$refs.plusMenuTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.plusMenuTree.getHalfCheckedKeys().join(','));
        this.userMenuDTO.reduceMenuIds = this.$refs.reduceMenuTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.reduceMenuTree.getHalfCheckedKeys().join(','));
        console.log("userMenuDTO:",this.userMenuDTO);
        userMenuUpdate(this.userMenuDTO).then(() => {
          this.dialogPermissionVisible = false;
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        });
      },
      rowClick(row, event, column){
        this.currentSelectedRow = row;
      },
      handleRoleAdd(){
        if(!this.currentSelectedRow){
          this.$message({
            message: '请选择一行哦',
            type: 'warning',
            showClose: false
          });
          return;
        }
        console.log("this.currentSelectedRow:",this.currentSelectedRow);
        this.role = [];
        for (var i = 0; i < this.currentSelectedRow.roleList.length; i++) {
          this.role[i] = this.currentSelectedRow.roleList[i].roleId;
        }
        this.getNodeData();
        this.dialogRoleVisible = true;
      },
      updateUserRole(){
        if(this.role.length==0){
          this.$message({
            message: '请选择角色信息',
            type: 'warning',
            showClose: false
          });
          return;
        }
        userRoleUpd(this.currentSelectedRow.userId,this.role).then((response)=>{
          this.$notify({
            title: "成功",
            message: "角色分配成功",
            type: "success",
            duration: 2000
          });
          this.getList(this.page);
          this.dialogRoleVisible = false;
        });
      },
      handlePasswordReset(){
        if(!this.currentSelectedRow){
          this.$message({
            message: '请选择一行哦',
            type: 'warning',
            showClose: false
          });
          return;
        }
        resetPassword(this.currentSelectedRow.userId).then((response) => {
          this.$notify({
            title: "成功",
            message: "初始密码重置成功",
            type: "success",
            duration: 2000
          });
        });
        this.getList(this.page);
        this.$refs.crud.setCurrentRow();
        //设置为默认值
        this.currentSelectedRow=undefined;
      },
    }
  };
</script>
<style lang="scss">
  .user {
    height: 100%;

    &__tree {
      padding-top: 3px;
      padding-right: 20px;
    }

    &__main {
      .el-card__body {
        padding-top: 0;
      }
    }
  }
</style>

